package top.huxy.web.config.messageConverter;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import top.huxy.web.core.Result;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * @author aproz
 * @Date 2022/5/18
 */
public class ResultMessageConverter implements HttpMessageConverter<Result> {
    @Override
    public List<MediaType> getSupportedMediaTypes(Class<?> clazz) {
        return getSupportedMediaTypes();
    }

    @Override
    public boolean canRead(Class<?> clazz, MediaType mediaType) {
        return false;
    }

    @Override
    public boolean canWrite(Class<?> clazz, MediaType mediaType) {
        return clazz.isAssignableFrom(Result.class);
    }

    @Override
    public List<MediaType> getSupportedMediaTypes() {
        List<MediaType> list = new LinkedList<>();
        list.add(MediaType.ALL);
        list.add(MediaType.APPLICATION_JSON);
        list.add(MediaType.APPLICATION_JSON_UTF8);
        return list;
    }

    @Override
    public Result read(Class<? extends Result> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    @Override
    public void write(Result result, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        outputMessage.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        outputMessage.getBody().write(JSON.toJSONBytes(result,JSONWriter.Feature.FieldBased));
    }
}
